<template>
  <div class="health-records">
    <el-container>
      <el-header class="page-header">
        <div class="header-content">
          <h2>健康档案管理</h2>
          <el-button type="primary" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回工作台
          </el-button>
        </div>
      </el-header>
      
      <el-main class="page-main">
        <!-- 搜索和筛选区域 -->
        <el-card class="search-card">
          <el-form :model="searchForm" inline>
            <el-form-item label="姓名">
              <el-input 
                v-model="searchForm.name" 
                placeholder="请输入就诊人姓名"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable style="width: 120px">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄范围">
              <el-input-number 
                v-model="searchForm.minAge" 
                placeholder="最小年龄"
                :min="0"
                :max="150"
                style="width: 120px"
              />
              <span class="age-separator">-</span>
              <el-input-number 
                v-model="searchForm.maxAge" 
                placeholder="最大年龄"
                :min="0"
                :max="150"
                style="width: 120px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 就诊人列表 -->
        <el-card class="list-card">
          <template #header>
            <div class="card-header">
              <span>就诊人列表 ({{ filteredPatients.length }})</span>
              <el-button type="primary" @click="refreshList">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          
          <el-table 
            :data="filteredPatients" 
            v-loading="loading"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="gender" label="性别" width="80">
              <template #default="{ row }">
                <el-tag :type="row.gender === 1 ? 'primary' : 'success'">
                  {{ row.gender === 1 ? '男' : '女' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="60" />
            <el-table-column prop="phone" label="联系电话" width="120" />
            <el-table-column prop="height" label="身高(cm)" width="80" />
            <el-table-column prop="weight" label="体重(kg)" width="80" />
            <el-table-column prop="bloodOxygen" label="血氧(%)" width="80" />
            <el-table-column prop="vision" label="视力" width="60" />
            <el-table-column prop="bloodPressure" label="血压" width="80" />
            <el-table-column prop="bloodSugar" label="血糖" width="80" />
            <el-table-column prop="bloodLipid" label="血脂" width="80" />
            <el-table-column prop="development" label="健康状况" width="80" />
            <el-table-column prop="otherConditions" label="其他" width="80" />
            <el-table-column prop="allergicHistory" label="过敏史" min-width="120" show-overflow-tooltip />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewPatient(row)"
                >
                  查看详情
                </el-button>
                <el-button 
                  type="warning" 
                  size="small" 
                  @click="editHealth(row)"
                >
                  修改健康指标
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>

    <!-- 就诊人详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="就诊人详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedPatient" class="patient-detail">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="姓名">{{ selectedPatient.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ selectedPatient.gender === 1 ? '男' : '女' }}
          </el-descriptions-item>
          <el-descriptions-item label="年龄">{{ selectedPatient.age }}岁</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedPatient.phone }}</el-descriptions-item>
                     <el-descriptions-item label="身高">{{ selectedPatient.height || '未测量' }}cm</el-descriptions-item>
           <el-descriptions-item label="体重">{{ selectedPatient.weight || '未测量' }}kg</el-descriptions-item>
           <el-descriptions-item label="血氧饱和度">{{ selectedPatient.bloodOxygen || '未测量' }}%</el-descriptions-item>
           <el-descriptions-item label="视力">{{ selectedPatient.vision || '未测量' }}</el-descriptions-item>
           <el-descriptions-item label="血压">{{ selectedPatient.bloodPressure || '未测量' }}mmHg</el-descriptions-item>
           <el-descriptions-item label="血糖">{{ selectedPatient.bloodSugar || '未测量' }}mmol/L</el-descriptions-item>
           <el-descriptions-item label="血脂">{{ selectedPatient.bloodLipid || '未测量' }}mmol/L</el-descriptions-item>
           <el-descriptions-item label="健康状况">{{ selectedPatient.development || '未测量' }}</el-descriptions-item>
           <el-descriptions-item label="其他情况">{{ selectedPatient.otherConditions || '未测量' }}</el-descriptions-item>
           <el-descriptions-item label="过敏史">{{ selectedPatient.allergicHistory || '无' }}</el-descriptions-item>
           <el-descriptions-item label="既往病史" :span="3">
             {{ selectedPatient.medicalHistory || '无' }}
           </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 修改健康指标对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改健康指标"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form 
        v-if="editForm" 
        :model="editForm" 
        :rules="editRules"
        ref="editFormRef"
        label-width="120px"
      >
        <el-form-item label="姓名">
          <el-input v-model="editForm.name" disabled />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身高" prop="height">
              <el-input 
                v-model="editForm.height" 
                placeholder="请输入身高，如：180"
                style="width: 100%"
              />
              <span class="unit">cm</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重" prop="weight">
              <el-input 
                v-model="editForm.weight" 
                placeholder="请输入体重，如：70"
                style="width: 100%"
              />
              <span class="unit">kg</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血氧饱和度" prop="bloodOxygen">
              <el-input 
                v-model="editForm.bloodOxygen" 
                placeholder="请输入血氧饱和度，如：98"
                style="width: 100%"
              />
              <span class="unit">%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视力" prop="vision">
              <el-input 
                v-model="editForm.vision" 
                placeholder="请输入视力，如：5.0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血压" prop="bloodPressure">
              <el-input 
                v-model="editForm.bloodPressure" 
                placeholder="请输入血压，如：120/80"
                style="width: 100%"
              />
              <span class="unit">mmHg</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血糖" prop="bloodSugar">
              <el-input 
                v-model="editForm.bloodSugar" 
                placeholder="请输入血糖，如：5.6"
                style="width: 100%"
              />
              <span class="unit">mmol/L</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血脂" prop="bloodLipid">
              <el-input 
                v-model="editForm.bloodLipid" 
                placeholder="请输入血脂，如：3.2"
                style="width: 100%"
              />
              <span class="unit">mmol/L</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="健康状况" prop="development">
              <el-input 
                v-model="editForm.development" 
                placeholder="请输入健康状况"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="其他情况" prop="otherConditions">
          <el-input 
            v-model="editForm.otherConditions" 
            placeholder="请输入其他情况"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="过敏史" prop="allergicHistory">
          <el-input 
            v-model="editForm.allergicHistory" 
            type="textarea" 
            :rows="3"
            placeholder="请输入过敏史，多个过敏源用逗号分隔"
          />
        </el-form-item>
        
        <el-form-item label="既往病史" prop="medicalHistory">
          <el-input 
            v-model="editForm.medicalHistory" 
            type="textarea" 
            :rows="3"
            placeholder="请输入既往病史"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmEdit"
            :loading="saving"
          >
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Search, 
  Refresh 
} from '@element-plus/icons-vue'
import { getPatientList, updatePatientHealth } from '../api/doctor'

const router = useRouter()
const loading = ref(false)
const saving = ref(false)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const selectedPatient = ref(null)
const editFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  gender: '',
  minAge: null,
  maxAge: null
})

// 编辑表单
const editForm = ref(null)

// 就诊人列表
const patients = ref([])

// 编辑表单验证规则
const editRules = {
  height: [
    { required: false, message: '请输入身高', trigger: 'blur' }
  ],
  weight: [
    { required: false, message: '请输入体重', trigger: 'blur' }
  ],
  bloodOxygen: [
    { required: false, message: '请输入血氧饱和度', trigger: 'blur' }
  ],
  vision: [
    { required: false, message: '请输入视力', trigger: 'blur' }
  ],
  bloodPressure: [
    { required: false, message: '请输入血压', trigger: 'blur' }
  ],
  bloodSugar: [
    { required: false, message: '请输入血糖', trigger: 'blur' }
  ],
  bloodLipid: [
    { required: false, message: '请输入血脂', trigger: 'blur' }
  ],
  development: [
    { required: false, message: '请输入健康状况', trigger: 'blur' }
  ],
  otherConditions: [
    { required: false, message: '请输入其他情况', trigger: 'blur' }
  ],
  allergicHistory: [
    { required: false, message: '请输入过敏史', trigger: 'blur' }
  ],
  medicalHistory: [
    { required: false, message: '请输入既往病史', trigger: 'blur' }
  ]
}

// 过滤后的就诊人列表
const filteredPatients = computed(() => {
  let filtered = patients.value

  if (searchForm.name) {
    filtered = filtered.filter(patient => 
      patient.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  if (searchForm.gender) {
    filtered = filtered.filter(patient => patient.gender === searchForm.gender)
  }

  if (searchForm.minAge !== null) {
    filtered = filtered.filter(patient => patient.age >= searchForm.minAge)
  }

  if (searchForm.maxAge !== null) {
    filtered = filtered.filter(patient => patient.age <= searchForm.maxAge)
  }

  return filtered
})

// 获取就诊人列表
const fetchPatients = async () => {
  try {
    loading.value = true
    const response = await getPatientList()
    if (response.code === 200) {
      patients.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取就诊人列表失败')
    }
  } catch (error) {
    console.error('获取就诊人列表失败:', error)
    ElMessage.error('获取就诊人列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.gender = ''
  searchForm.minAge = null
  searchForm.maxAge = null
}

// 刷新列表
const refreshList = () => {
  fetchPatients()
}

// 查看就诊人详情
const viewPatient = (patient) => {
  selectedPatient.value = patient
  detailDialogVisible.value = true
}

// 编辑健康指标
const editHealth = (patient) => {
  editForm.value = {
    id: patient.id,
    name: patient.name,
    height: patient.height,
    weight: patient.weight,
    bloodOxygen: patient.bloodOxygen,
    vision: patient.vision,
    bloodPressure: patient.bloodPressure,
    bloodSugar: patient.bloodSugar,
    bloodLipid: patient.bloodLipid,
    development: patient.development,
    otherConditions: patient.otherConditions,
    allergicHistory: patient.allergicHistory,
    medicalHistory: patient.medicalHistory
  }
  editDialogVisible.value = true
}

// 确认修改
const confirmEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saving.value = true
    
    const response = await updatePatientHealth(editForm.value)
    
    if (response.code === 200) {
      ElMessage.success('健康指标修改成功')
      
      // 更新本地数据
      const index = patients.value.findIndex(p => p.id === editForm.value.id)
      if (index !== -1) {
        Object.assign(patients.value[index], response.data)
      }
      
      editDialogVisible.value = false
      editForm.value = null
    } else {
      ElMessage.error(response.message || '修改失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    saving.value = false
  }
}

// 返回工作台
const goBack = () => {
  router.push('/doctor-dashboard')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPatients()
})
</script>

<style scoped>
.health-records {
  height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.page-main {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.age-separator {
  margin: 0 10px;
  color: #606266;
}

.list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-detail {
  padding: 20px 0;
}

.unit {
  margin-left: 10px;
  color: #606266;
}

:deep(.el-row) {
  margin-bottom: 0;
}

:deep(.el-col) {
  padding-bottom: 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-descriptions__content) {
  color: #606266;
}
</style>
